//
//  UIFPSLabel.swift
//  TTCOM-iOS
//
//  Created by Toj on 8/12/22.
//

import UIKit

private let defaultSize = CGSize(width: 55, height: 20)
open class UIFPSLabel: UILabel {
    
    private lazy var timer: CADisplayLink = {
        let timer = CADisplayLink(target: self, selector: #selector(updateValues(timer:)))
        return timer
    }()
    
    private var fpsCount = 1
    private lazy var beforTime = CACurrentMediaTime()
    private var formatString: String = "FPS: %d"
    
    open override var frame: CGRect {
        set {
            super.frame = newValue
        }
        
        get {
            return super.frame
        }
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        
        let selfWidth = frame.width
        let selfHeight = frame.height
        guard selfWidth == 0 || selfHeight == 0 else {
            return
        }
        
        let superWidth = superview?.frame.width ?? 0
        let superHeight = superview?.frame.height ?? 0
        guard superWidth > 0 && superHeight > 0 else {
            return
        }
        let x = (superWidth - defaultSize.width) * 0.5
        frame = CGRect(x: x, y: .nav_barFullHeight, width: defaultSize.width, height: defaultSize.height)
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        textColor = .red
        font = UIFont.systemFont(ofSize: 14)
        timer.add(to: .main, forMode: .common)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func updateValues(timer: CADisplayLink) {
        
        fpsCount += 1
        let delta = timer.timestamp - beforTime
        // 累积时间 小于1秒
        if delta < 1 { return }
        // 计算1秒内多少帧率
        let fps = Double(fpsCount) / delta
        text = String(format: formatString, Int(round(fps)))
        
        //重置
        beforTime = timer.timestamp
        fpsCount = 0
    }
}
